/**
 * 团长管理
 */
layui.define(['table', 'form', 'dropdown', 'util', 'common'], function (exports) {
    var $ = layui.$
        , admin = layui.admin
        , setter = layui.setter
        , view = layui.view
        , table = layui.table
        , form = layui.form
        , dropdown = layui.dropdown
        , upload = layui.upload
        , util = layui.util
        , element = layui.element
        , common = layui.common;

    let atOnceUploadFileMaxNumber, singleFileMaxLength, isEnablePapaerInvoice;
    let dropdownButtonData = [{
        id: 'batchUploadElectronic',
        title: '批量上传电子发票'
    }];

    function isJsonStringEmpty(jsonString) {
        // 首先，检查字符串是否为null或空字符串  
        if (jsonString === null || jsonString === "" || jsonString.trim() === "") {
            return true;
        }

        // 尝试将字符串解析为JSON  
        try {
            const parsed = JSON.parse(jsonString);

            // 检查是否为空对象或空数组  
            if (Array.isArray(parsed) && parsed.length === 0) {
                return true;
            }
            if (typeof parsed === 'object' && parsed !== null && Object.keys(parsed).length === 0) {
                return true;
            }

            // 如果不是空对象或空数组，则认为字符串不是空的  
            return false;
        } catch (e) {
            // 如果解析出错，则不是有效的JSON字符串，这里可以根据需求返回false或抛出错误  
            // 这里我们简单返回false，表示它不是空的（因为我们只关心空的情况）  
            return false;
        }

        // 理论上，如果字符串是有效的JSON但不符合上述空的条件，这里不会执行  
        // 但为了代码的完整性，我们可以显式地返回一个false（尽管上面的catch块已经处理了所有情况）  
        return false;
    }

    function addLog(logObj) {
        $.ajax({
            url: setter.baseConfig.apiHost + '/api/log/add' //实际使用请改成服务端真实接口
            , type: 'post'
            , contentType: "application/json"
            , data: JSON.stringify(logObj)
            , beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
            }
            , success: function (res) {
                if (res.errorCode != '00000') {
                    //layer.msg(res.errorMessage, {
                    //    offset: '15px'
                    //    , icon: 2
                    //    , time: 3000
                    //});

                    return false;
                }
            }
        });
    }

    function getWebSiteConfig() {
        $.ajax({
            url: setter.baseConfig.apiHost + '/api/system/getwebsiteconfig' //实际使用请改成服务端真实接口
            , type: 'post'
            , contentType: "application/json"
            , async: false // 设置为同步请求，确保能实时获取到网站配置
            //, data: JSON.stringify(data)
            , beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
            }
            , success: function (res) {
                console.log(res);
                if (res.errorCode != '00000') {
                    layer.msg(res.errorMessage, {
                        offset: '15px'
                        , icon: 2
                        , time: 3000
                    });

                    return false;
                }

                atOnceUploadFileMaxNumber = Number(res.data.atOnceUploadFileMaxNumber);
                singleFileMaxLength = Number(res.data.singleFileMaxLength);
                isEnablePapaerInvoice = res.data.isEnablePapaerInvoice === 'on';
            }
        });
    }

    function customAlertTip(content) {
        layer.alert(content, {
            time: 5 * 1000,
            offset: 'auto',
            anim: 'slideDown',
            success: function (layero, index) {
                var timeNum = this.time / 1000, setText = function (start) {
                    layer.title('<span class="layui-font-red">' + (start ? timeNum : --timeNum) + '</span> 秒后自动关闭', index);
                };
                setText(!0);
                this.timer = setInterval(setText, 1000);
                if (timeNum <= 0) clearInterval(this.timer);
            },
            end: function () {
                clearInterval(this.timer);
            }
        });
    }

    //获取网站设置
    //getWebSiteConfig();

    //团长管理
    table.render({
        elem: '#LAY-leader-manage'
        , url: setter.baseConfig.apiHost + '/api/leader/getpagingleaders'
        , toolbar: '#toolbarDemo'
        , defaultToolbar: []
        , method: 'post'
        , contentType: "application/json"
        , headers: { //通过 request 头传递
            Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
        }
        , parseData: function (res) { // res 即为原始返回的数据
            return {
                "code": res.errorCode, // 解析接口状态
                "msg": res.errorMessage, // 解析提示文本
                "count": res.data.totalCount, // 解析数据长度
                "data": res.data.entities // 解析数据列表
            };
        }
        , cols: [[
            { type: 'numbers', fixed: 'left', title: '序号' }
            , { field: 'id', title: 'Id', hide: true }
            , { field: 'createdTime', title: '创建时间', width: 180 }
            , { field: 'leaderId', title: '团长Id', width: 120, templet: '#ID-table-leader-templet-leaderId' }
            , { field: 'name', title: '团长名称', minWidth: 120, templet: '#ID-table-leader-templet-leaderName' }
            , { field: 'isEnabled', title: '状态', minWidth: 100, templet: '#ID-table-leader-templet-isEnabled' }
            , { field: 'channel', title: '类别', minWidth: 110 }
            , { field: 'productCountThirtyDays', title: '合作商品数(30日)' }
            , { field: 'promoterCountThirtyDays', title: '服务达人数(30日)' }
            , { field: 'avgCommissionRateThirtyDays', title: '平均佣金率(30日)' }
            , { field: 'productAvgPriceThirtyDays', title: '商品均价(30日)' }
            , { field: 'productCount', title: '商品数', width: 100 }
            , { title: '操作', width: 180, fixed: 'right', toolbar: '#table-leader-admin', align: 'center' }
        ]]
        , page: true
        , limit: 20
        , limits: [10, 20, 30, 40, 50]
        , text: { none: '无数据' }
    });

    // 工具栏事件
    table.on('toolbar(LAY-leader-manage)', function (obj) {
        var id = obj.config.id;
        var checkStatus = table.checkStatus(id);
        var othis = lay(this);
        switch (obj.event) {
            case 'viewResult':
                admin.popup({
                    title: '查看识别结果'
                    , area: ['80%', '80%']
                    , id: 'LAY-popup-myinvoice-viewResult'
                    , success: function (layero, index) {
                        view(this.id).render('myinvoice/viewform').done(function () {
                            form.render(null, 'layadmin-myinvoice-viewformlist');

                            //查看识别结果
                            table.render({
                                elem: '#LAY-myinvoice-viewresult-manage'
                                , url: setter.baseConfig.apiHost + '/api/myinvoice/getpaginginvoicelots'
                                //, toolbar: '#toolbarDemo'
                                //, defaultToolbar: []
                                , method: 'post'
                                , contentType: "application/json"
                                , headers: { //通过 request 头传递
                                    Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
                                }
                                , parseData: function (res) { // res 即为原始返回的数据
                                    return {
                                        "code": res.errorCode, // 解析接口状态
                                        "msg": res.errorMessage, // 解析提示文本
                                        "count": res.data.totalCount, // 解析数据长度
                                        "data": res.data.entities // 解析数据列表
                                    };
                                }
                                , cols: [[
                                    { type: 'numbers', fixed: 'left' }
                                    , { field: 'id', title: 'Id', hide: true }
                                    , { field: 'uploadTime', title: '上传时间', width: 200 }
                                    , { field: 'lotNo', title: '批次号', width: 180 }
                                    , { field: 'uploadTypeName', title: '上传类型', width: 180 }
                                    , { field: 'userName', title: '用户名', width: 180 }
                                    , { field: 'successCount', title: '成功数量', templet: '#successCountTpl' }
                                    , { field: 'failCount', title: '失败数量', templet: '#failCountTpl' }
                                    //, { title: '操作', width: 240, fixed: 'right', toolbar: '#table-useradmin-webuser' }
                                ]]
                                , page: true
                                , limit: 20
                                , limits: [10, 20, 30, 40, 50]
                                , text: { none: '无数据' }
                            });

                            //依据用户身份显示和隐藏列
                            $.ajax({
                                url: setter.baseConfig.apiHost + '/api/user/getloginuserinfo' //实际使用请改成服务端真实接口
                                , type: 'post'
                                , contentType: "application/json"
                                //, data: JSON.stringify(field)
                                , beforeSend: function (xhr) {
                                    xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                }
                                , success: function (res) {
                                    if (res.errorCode != '00000') {
                                        layer.msg(res.errorMessage, {
                                            offset: '15px'
                                            , icon: 2
                                            , time: 3000
                                        });
                                        return false;
                                    }

                                    var role = res.data.role;
                                    if (role != 'ADMIN') {
                                        table.hideCol('LAY-myinvoice-viewresult-manage', {
                                            field: 'userName', // 对应表头的 field 属性值
                                            hide: true // `true` or `false`
                                        });
                                    }
                                }
                            });

                            // 查看识别结果详情
                            table.on('tool(LAY-myinvoice-viewresult-manage)', function (obj) {
                                var data = obj.data; // 得到当前行数据
                                var dataCache = obj.dataCache; // 得到当前行缓存数据，包含特定字段 --- 2.8.8+
                                var index = obj.index; // 得到当前行索引
                                var layEvent = obj.event; // 获得元素对应的 lay-event 属性值
                                var tr = obj.tr; // 得到当前行 <tr> 元素的 jQuery 对象
                                var options = obj.config; // 获取当前表格基础属性配置项
                                var col = obj.getCol(); // 得到当前列的表头配置属性 -- v2.8.3 新增
                                console.log(obj); // 查看对象所有成员

                                // 根据 lay-event 的值执行不同操作
                                if (layEvent === 'detail') { //查看
                                    // do somehing
                                } else if (layEvent === 'del') { //删除
                                    layer.confirm('确定删除吗？', function (index) {
                                        obj.del(); // 删除对应行（tr）的 DOM 结构，并更新缓存
                                        layer.close(index);

                                        // 向后端发送删除请求，执行完毕后，可通过 reloadData 方法完成数据重载
                                        /*
                                        table.reloadData(id, {
                                          scrollPos: 'fixed'  // 保持滚动条位置不变 - v2.7.3 新增
                                        });
                                        */
                                    });
                                } else if (layEvent === 'edit') { //编辑
                                    // do something

                                    // 同步更新缓存对应的值
                                    // 该方法仅为前端层面的临时更新，在实际业务中需提交后端请求完成真实的数据更新。
                                    obj.update({
                                        username: '123',
                                        title: 'abc'
                                    });
                                    // 若需更新其他包含自定义模板并可能存在关联的列视图，可在第二个参数传入 true
                                    obj.update({
                                        username: '123'
                                    }, true); // 注：参数二传入 true 功能为 v2.7.4 新增

                                    // 当发送后端请求成功后，可再通过 reloadData 方法完成数据重载
                                    /*
                                    table.reloadData(id, {
                                      scrollPos: 'fixed'  // 保持滚动条位置不变 - v2.7.3 新增
                                    });
                                    */
                                } else if (layEvent === 'viewInfoSuccess') {
                                    admin.popup({
                                        title: '查看识别详情'
                                        , area: ['80%', '75%']
                                        , id: 'LAY-popup-myinvoice-viewinfosuccess'
                                        , success: function (layero, index) {
                                            view(this.id).render('myinvoice/viewinfoform').done(function () {
                                                //form.render(null, 'layuiadmin-form-myinvoiceadmin');

                                                //查看识别详情
                                                table.render({
                                                    elem: '#LAY-myinvoice-viewinforesult-manage'
                                                    , url: setter.baseConfig.apiHost + '/api/myinvoice/getinvoicelotinfos'
                                                    //, toolbar: '#toolbarDemo'
                                                    //, defaultToolbar: []
                                                    , where: { lotId: data.id, isSuccess: true }
                                                    , method: 'post'
                                                    , contentType: "application/json"
                                                    , headers: { //通过 request 头传递
                                                        Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
                                                    }
                                                    , parseData: function (res) { // res 即为原始返回的数据
                                                        return {
                                                            "code": res.errorCode, // 解析接口状态
                                                            "msg": res.errorMessage, // 解析提示文本
                                                            "count": res.data.totalCount, // 解析数据长度
                                                            "data": res.data.entities // 解析数据列表
                                                        };
                                                    }
                                                    , cols: [[
                                                        { type: 'numbers', fixed: 'left' }
                                                        , { field: 'id', title: 'Id', hide: true }
                                                        , { field: 'fileName', title: '文件名' }
                                                        , { field: 'billTypeName', title: '票据类型' }
                                                        , { field: 'issueDate', title: '开票日期' }
                                                        , { field: 'fee', title: '金额' }
                                                        //, { field: 'failReason', title: '失败原因' }
                                                        //, { title: '操作', width: 240, fixed: 'right', toolbar: '#table-useradmin-webuser' }
                                                    ]]
                                                    , page: true
                                                    , limit: 20
                                                    , limits: [10, 20, 30, 40, 50]
                                                    , text: { none: '无数据' }
                                                });
                                            });
                                        }
                                    });
                                } else if (layEvent === 'viewInfoFail') {
                                    admin.popup({
                                        title: '查看识别详情'
                                        , area: ['80%', '75%']
                                        , id: 'LAY-popup-myinvoice-viewinfosuccess'
                                        , success: function (layero, index) {
                                            view(this.id).render('myinvoice/viewinfoform').done(function () {
                                                //form.render(null, 'layuiadmin-form-myinvoiceadmin');

                                                //查看识别详情
                                                table.render({
                                                    elem: '#LAY-myinvoice-viewinforesult-manage'
                                                    , url: setter.baseConfig.apiHost + '/api/myinvoice/getinvoicelotinfos'
                                                    //, toolbar: '#toolbarDemo'
                                                    //, defaultToolbar: []
                                                    , where: { lotId: data.id, isSuccess: false }
                                                    , method: 'post'
                                                    , contentType: "application/json"
                                                    , headers: { //通过 request 头传递
                                                        Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]
                                                    }
                                                    , parseData: function (res) { // res 即为原始返回的数据
                                                        return {
                                                            "code": res.errorCode, // 解析接口状态
                                                            "msg": res.errorMessage, // 解析提示文本
                                                            "count": res.data.totalCount, // 解析数据长度
                                                            "data": res.data.entities // 解析数据列表
                                                        };
                                                    }
                                                    , cols: [[
                                                        { type: 'numbers', fixed: 'left' }
                                                        , { field: 'id', title: 'Id', hide: true }
                                                        , { field: 'fileName', title: '文件名' }
                                                        //, { field: 'billTypeName', title: '票据类型' }
                                                        //, { field: 'issueDate', title: '开票日期' }
                                                        //, { field: 'fee', title: '金额' }
                                                        , { field: 'failReason', title: '失败原因' }
                                                        //, { title: '操作', width: 240, fixed: 'right', toolbar: '#table-useradmin-webuser' }
                                                    ]]
                                                    , page: true
                                                    , limit: 20
                                                    , limits: [10, 20, 30, 40, 50]
                                                    , text: { none: '无数据' }
                                                });
                                            });
                                        }
                                    });
                                }
                            });
                        });
                    }
                });
                break;
            case 'typeIn':
                var index1 = admin.popup({
                    title: '手工录入发票'
                    , area: ['50%', '50%']
                    , id: 'LAY-popup-myinvoice-typeIn'
                    , success: function (layero, index) {
                        view(this.id).render('myinvoice/typeinform').done(function () {
                            form.render(null, 'layadmin-myinvoice-typeinform');

                            //选择票据类型
                            // select 事件
                            form.on('select(myinvoice-typeinform-select-filter)', function (data) {
                                console.log(data);
                                var elem = data.elem; // 获得 select 原始 DOM 对象
                                var value = data.value; // 获得被选中的值
                                var othis = data.othis; // 获得 select 元素被替换后的 jQuery 对象

                                switch (value) {
                                    case '1'://增值税普通发票
                                    case '2'://增值税专用发票
                                        var index2 = admin.popup({
                                            title: '手工录入发票'
                                            , area: ['60%', '60%']
                                            , id: 'LAY-popup-myinvoice-typeInVatElectronicInvoice'
                                            , success: function (layero, index) {
                                                view(this.id).render('myinvoice/typeinvatinvoiceform', { invoiceType: value }).done(function () {
                                                    form.render(null, 'layadmin-myinvoice-typeinvatinvoiceform');

                                                    //处理自定义事件
                                                    util.on({
                                                        cancel: function () {
                                                            layer.close(index2);
                                                        }
                                                    });

                                                    // 提交事件
                                                    form.on('submit(LAY-myinvoice-typeinvatinvoice-search)', function (data) {
                                                        var field = data.field; // 获取表单全部字段值
                                                        var elem = data.elem; // 获取当前触发事件的元素 DOM 对象，一般为 button 标签
                                                        var elemForm = data.form; // 获取当前表单域的 form 元素对象，若容器为 form 标签才会返回。
                                                        let projectArr = [];

                                                        //获取项目明细
                                                        $('#ID-table-myinvoice-typeinvatinvoiceform tbody tr').each(function () {
                                                            var name = $(this).find(':input[name=name]').val();
                                                            var specification = $(this).find(':input[name=specification]').val();
                                                            var unit = $(this).find(':input[name=unit]').val();
                                                            var quantity = $(this).find(':input[name=quantity]').val();
                                                            var unitPrice = $(this).find(':input[name=unitPrice]').val();
                                                            var price = $(this).find(':input[name=price]').val();
                                                            var taxRate = $(this).find(':input[name=taxRate]').val();
                                                            var tax = $(this).find(':input[name=tax]').val();
                                                            var projectObj = {
                                                                name: name,
                                                                specification: specification,
                                                                unit: unit,
                                                                quantity: quantity,
                                                                unitPrice: unitPrice,
                                                                price: price,
                                                                taxRate: taxRate,
                                                                tax: tax
                                                            };
                                                            projectArr.push(projectObj);
                                                        });
                                                        field.projects = projectArr;
                                                        console.log(field);

                                                        //AJAX请求
                                                        $.ajax({
                                                            url: setter.baseConfig.apiHost + '/api/myinvoice/typeinvatinvoice' //实际使用请改成服务端真实接口
                                                            , type: 'post'
                                                            , contentType: "application/json"
                                                            , data: JSON.stringify(field)
                                                            , beforeSend: function (xhr) {
                                                                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                                            }
                                                            , success: function (res) {
                                                                if (res.errorCode != '00000') {
                                                                    layer.msg(res.errorMessage, {
                                                                        offset: '15px'
                                                                        , icon: 2
                                                                        , time: 3000
                                                                    });
                                                                    return false;
                                                                }

                                                                //登入成功的提示与跳转
                                                                layer.msg('补录成功', {
                                                                    offset: '15px'
                                                                    , icon: 1
                                                                    , time: 3000
                                                                });

                                                                layui.table.reload('LAY-leader-manage'); //重载表格
                                                                layer.close(index2);
                                                                layer.close(index1);
                                                            }
                                                        });
                                                    });
                                                });
                                            }
                                        });
                                        //最大化
                                        layer.full(index2);
                                        break;
                                    case '3'://机票行程单
                                        var index4 = admin.popup({
                                            title: '手工录入发票'
                                            , area: ['60%', '60%']
                                            , id: 'LAY-popup-myinvoice-typeInFlightItinerary'
                                            , success: function (layero, index) {
                                                view(this.id).render('myinvoice/typeinitineraryform', { invoiceType: value }).done(function () {
                                                    form.render(null, 'layadmin-myinvoice-typeinitineraryform');

                                                    //处理自定义事件
                                                    util.on({
                                                        cancel: function () {
                                                            layer.close(index4);
                                                        }
                                                    });

                                                    // 提交事件
                                                    form.on('submit(LAY-myinvoice-typeinitinerary-search)', function (data) {
                                                        var field = data.field; // 获取表单全部字段值
                                                        var elem = data.elem; // 获取当前触发事件的元素 DOM 对象，一般为 button 标签
                                                        var elemForm = data.form; // 获取当前表单域的 form 元素对象，若容器为 form 标签才会返回。
                                                        let flightInfoArr = [];

                                                        //获取航班明细
                                                        $('#ID-table-myinvoice-typeinitineraryform tbody tr').each(function () {
                                                            var from = $(this).find(':input[name=from]').val();
                                                            var to = $(this).find(':input[name=to]').val();
                                                            var carrier = $(this).find(':input[name=carrier]').val();
                                                            var flightNumber = $(this).find(':input[name=flightNumber]').val();
                                                            var seatClass = $(this).find(':input[name=seatClass]').val();
                                                            var flightDate = $(this).find(':input[name=flightDate]').val();
                                                            var flightTime = $(this).find(':input[name=flightTime]').val();
                                                            var fareBasis = $(this).find(':input[name=fareBasis]').val();
                                                            var freeBaggage = $(this).find(':input[name=freeBaggage]').val();

                                                            var flightInfoObj = {
                                                                from: from,
                                                                to: to,
                                                                carrier: carrier,
                                                                flightNumber: flightNumber,
                                                                seatClass: seatClass,
                                                                flightDate: flightDate,
                                                                flightTime: flightTime,
                                                                fareBasis: fareBasis,
                                                                freeBaggage: freeBaggage
                                                            };
                                                            flightInfoArr.push(flightInfoObj);
                                                        });
                                                        field.flights = flightInfoArr;
                                                        console.log(field);

                                                        //AJAX请求
                                                        $.ajax({
                                                            url: setter.baseConfig.apiHost + '/api/myinvoice/typeinitinerary' //实际使用请改成服务端真实接口
                                                            , type: 'post'
                                                            , contentType: "application/json"
                                                            , data: JSON.stringify(field)
                                                            , beforeSend: function (xhr) {
                                                                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                                            }
                                                            , success: function (res) {
                                                                if (res.errorCode != '00000') {
                                                                    layer.msg(res.errorMessage, {
                                                                        offset: '15px'
                                                                        , icon: 2
                                                                        , time: 3000
                                                                    });
                                                                    return false;
                                                                }

                                                                //登入成功的提示与跳转
                                                                layer.msg('补录成功', {
                                                                    offset: '15px'
                                                                    , icon: 1
                                                                    , time: 3000
                                                                });

                                                                layui.table.reload('LAY-leader-manage'); //重载表格
                                                                layer.close(index4);
                                                                layer.close(index1);
                                                            }
                                                        });
                                                    });

                                                });
                                            }
                                        });
                                        //最大化
                                        layer.full(index4);
                                        break;
                                    case '5'://增值税电子普通发票
                                    case '6'://增值税电子专用发票
                                        var index5 = admin.popup({
                                            title: '手工录入发票'
                                            , area: ['60%', '60%']
                                            , id: 'LAY-popup-myinvoice-typeInOldVatInvoice'
                                            , success: function (layero, index) {
                                                view(this.id).render('myinvoice/typeinoldvatinvoiceform', { invoiceType: value }).done(function () {
                                                    form.render(null, 'layadmin-myinvoice-typeinoldvatinvoiceform');

                                                    //处理自定义事件
                                                    util.on({
                                                        typeInOldVatInvoiceCancel: function () {
                                                            layer.close(index5);
                                                        }
                                                    });

                                                    // 提交事件
                                                    form.on('submit(LAY-myinvoice-typeinoldvatinvoice-search)', function (data) {
                                                        var field = data.field; // 获取表单全部字段值
                                                        var elem = data.elem; // 获取当前触发事件的元素 DOM 对象，一般为 button 标签
                                                        var elemForm = data.form; // 获取当前表单域的 form 元素对象，若容器为 form 标签才会返回。
                                                        let projectArr = [];

                                                        //获取项目明细
                                                        $('#ID-table-myinvoice-typeinoldvatinvoiceform tbody tr').each(function () {
                                                            var name = $(this).find(':input[name=name]').val();
                                                            var specification = $(this).find(':input[name=specification]').val();
                                                            var unit = $(this).find(':input[name=unit]').val();
                                                            var quantity = $(this).find(':input[name=quantity]').val();
                                                            var unitPrice = $(this).find(':input[name=unitPrice]').val();
                                                            var price = $(this).find(':input[name=price]').val();
                                                            var taxRate = $(this).find(':input[name=taxRate]').val();
                                                            var tax = $(this).find(':input[name=tax]').val();
                                                            var projectObj = {
                                                                name: name,
                                                                specification: specification,
                                                                unit: unit,
                                                                quantity: quantity,
                                                                unitPrice: unitPrice,
                                                                price: price,
                                                                taxRate: taxRate,
                                                                tax: tax
                                                            };
                                                            projectArr.push(projectObj);
                                                        });
                                                        field.projects = projectArr;
                                                        console.log(field);

                                                        //AJAX请求
                                                        $.ajax({
                                                            url: setter.baseConfig.apiHost + '/api/myinvoice/typeinvatinvoice' //实际使用请改成服务端真实接口
                                                            , type: 'post'
                                                            , contentType: "application/json"
                                                            , data: JSON.stringify(field)
                                                            , beforeSend: function (xhr) {
                                                                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                                            }
                                                            , success: function (res) {
                                                                if (res.errorCode != '00000') {
                                                                    layer.msg(res.errorMessage, {
                                                                        offset: '15px'
                                                                        , icon: 2
                                                                        , time: 3000
                                                                    });
                                                                    return false;
                                                                }

                                                                //登入成功的提示与跳转
                                                                layer.msg('补录成功', {
                                                                    offset: '15px'
                                                                    , icon: 1
                                                                    , time: 3000
                                                                });

                                                                layui.table.reload('LAY-leader-manage'); //重载表格
                                                                layer.close(index5);
                                                                layer.close(index1);
                                                            }
                                                        });
                                                    });
                                                });
                                            }
                                        });
                                        //最大化
                                        layer.full(index5);
                                        break;
                                }

                            });
                        });
                    }
                });
                break;
            case 'batchUploadInvoice':
                admin.popup({
                    title: '批量上传发票（电子发票）'
                    , area: ['80%', '80%']
                    , id: 'LAY-popup-myinvoice-uploadElectronicInvoice'
                    , success: function (layero, index) {
                        view(this.id).render('myinvoice/uploadelectronicform', {
                            atOnceUploadFileMaxNumber: atOnceUploadFileMaxNumber,
                            singleFileMaxLength: singleFileMaxLength / 1024
                        }).done(function () {
                            form.render(null, 'layuiadmin-form-myinvoice-upload-electronic');
                            //引导OFD提示
                            customAlertTip('OFD格式电子发票识别准确率更高，速度更快，推荐您优先选择OFD格式！');

                            //开启提交
                            form.on('submit(LAY-upload-electronic-front-submit)', function (data) {
                                var field = data.field; //获取提交的字段

                                //提交 Ajax 成功后，关闭当前弹层并重载表格
                                var postData = $('#hid-myinvoice-upload-electronic').val();
                                if (isJsonStringEmpty(postData)) {
                                    console.log(postData);
                                    layer.msg('请先选择和上传文件!');

                                    //将日志POST到后台便于查看
                                    let logObj = {
                                        logType: '2',
                                        message: postData,
                                        detail: postData
                                    };
                                    addLog(logObj);

                                    return false;
                                }

                                $.ajax({
                                    url: setter.baseConfig.apiHost + '/api/myinvoice/submitrecognize' //实际使用请改成服务端真实接口
                                    , type: 'post'
                                    , contentType: "application/json"
                                    , data: JSON.stringify({
                                        data: JSON.parse(postData),
                                        uploadType: '1',
                                        comment: field.comment
                                    })
                                    , beforeSend: function (xhr) {
                                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                    }
                                    , success: function (res) {
                                        if (res.errorCode != '00000') {
                                            layer.msg(res.errorMessage, {
                                                offset: '15px'
                                                , icon: 2
                                                , time: 3000
                                            });

                                            return false;
                                        }

                                        //提交成功提示
                                        customAlertTip('提交成功，您可以点击"查看识别结果"按钮进入查看识别结果页面！');

                                        layui.table.reload('LAY-leader-manage'); //重载表格
                                        layer.close(index); //执行关闭
                                    }
                                });
                            });

                            // 制作多文件上传表格
                            let uploadElectronicFileArr = [];
                            let loadElectronicIndex;
                            var uploadElectronicListIns = upload.render({
                                elem: '#ID-upload-electronic-files',
                                elemList: $('#ID-upload-electronic-files-list'), // 列表元素对象
                                url: setter.baseConfig.apiHost + '/api/myinvoice/upload?uploadType=1', //实际使用请改成服务端真实接口
                                headers: { Authorization: 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName] },
                                accept: 'file',
                                acceptMime: 'application/ofd,application/pdf',
                                //exts: 'pdf|ofd|xml',
                                multiple: true,
                                number: atOnceUploadFileMaxNumber,
                                auto: false,
                                bindAction: '#ID-upload-electronic-files-action',
                                size: singleFileMaxLength, //单个文件最大1024KB
                                choose: function (obj) {
                                    var that = this;
                                    var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列
                                    // 读取本地文件
                                    obj.preview(function (index, file, result) {
                                        var tr = $(['<tr id="upload-' + index + '">',
                                        '<td>' + file.name + '</td>',
                                        '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>',
                                        '<td><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>',
                                            '<td>',
                                            '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
                                            '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',
                                            '</td>',
                                            '</tr>'].join(''));

                                        // 单个重传
                                        tr.find('.demo-reload').on('click', function () {
                                            obj.upload(index, file);
                                        });

                                        // 删除
                                        tr.find('.demo-delete').on('click', function () {
                                            delete files[index]; // 删除对应的文件
                                            tr.remove(); // 删除表格行
                                            // 清空 input file 值，以免删除后出现同名文件不可选
                                            var next = uploadElectronicListIns.config.elem.next();
                                            if (next != undefined && next != null && next.length > 0) {
                                                uploadElectronicListIns.config.elem.next()[0].value = '';
                                            }
                                        });
                                        that.elemList.append(tr);
                                        element.render('progress'); // 渲染新加的进度条组件
                                    });
                                },
                                before: function (obj) { // obj 参数同 choose
                                    loadElectronicIndex = layer.msg('正在上传', {
                                        icon: 16,
                                        shade: 0.3,
                                        time: 0
                                    });

                                    // 若返回 false，则表明阻止上传
                                    /*
                                    if(true){
                                      return false;
                                    }
                                    */

                                    //当点击开始上传按钮后先将提交识别按钮置灰，直到全部文件上传完毕
                                    $('#ID-upload-electronic-form-submit').addClass('layui-btn-disabled');

                                },
                                done: function (res, index, upload) { // 成功的回调
                                    if (res.isSuccess == true) {
                                        // do something // 比如将 res 返回的图片链接保存到隐藏域
                                        let item = {
                                            fileName: res.data.fileName,
                                            filePath: res.data.filePath
                                        };
                                        uploadElectronicFileArr.push(item);
                                        return;
                                    }
                                    this.error(index, upload);
                                },
                                allDone: function (obj) { // 多文件上传完毕后的状态回调
                                    console.log(obj);

                                    //一起将上传的文件保存到隐藏字段中
                                    let uploadedFilesArrJson = JSON.stringify(uploadElectronicFileArr)
                                    $('#hid-myinvoice-upload-electronic').val(uploadedFilesArrJson);

                                    //当点击开始上传按钮后先将提交识别按钮置灰，直到全部文件上传完毕
                                    $('#ID-upload-electronic-form-submit').removeClass('layui-btn-disabled');

                                    //关闭loading
                                    layer.close(loadElectronicIndex);
                                },
                                error: function (index, upload) { // 错误回调
                                    var that = this;
                                    var tr = that.elemList.find('tr#upload-' + index);
                                    var tds = tr.children();
                                    // 显示重传
                                    tds.eq(3).find('.demo-reload').removeClass('layui-hide');
                                },
                                progress: function (n, elem, e, index) { // 注意：index 参数为 layui 2.6.6 新增
                                    element.progress('progress-demo-' + index, n + '%'); // 执行进度条。n 即为返回的进度百分比
                                }
                            });
                        });
                    }
                });
                break;
            case 'add':
                admin.popup({
                    title: '新增团长'
                    , area: ['800px', '600px']
                    , id: 'LAY-popup-leader-add'
                    , success: function (layero, index) {
                        view(this.id).render('leader/addform').done(function () {
                            form.render(null, 'layuiadmin-form-leaderadmin');

                            //处理自定义事件
                            util.on({
                                leaderaddformcancel: function () {
                                    layer.close(index);
                                },
                                getLeaderByName: function () {
                                    //清除数据和禁用按钮
                                    $('#ID-input-leader-addform-leaderId').val('');
                                    $("#ID-img-leader-addform-iconUrl").attr("src", '');
                                    $('#ID-button-leader-addform-getLeaderByName').addClass('layui-btn-disabled');

                                    const leaderName = $('#ID-input-leader-addform-leaderName').val();
                                    if (leaderName.trim().length == 0) {
                                        layer.msg('团长名称不能为空！');
                                        $('#ID-button-leader-addform-getLeaderByName').removeClass('layui-btn-disabled');
                                        return false;
                                    }
                                    const postData = {
                                        leaderName: leaderName
                                    };

                                    //AJAX请求
                                    $.ajax({
                                        url: setter.baseConfig.apiHost + '/api/leader/getleaders' //实际使用请改成服务端真实接口
                                        , type: 'post'
                                        , contentType: "application/json"
                                        , data: JSON.stringify(postData)
                                        , beforeSend: function (xhr) {
                                            xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                        }
                                        , success: function (res) {
                                            console.log(res);
                                            if (res.errorCode != '00000') {
                                                layer.msg(res.errorMessage, {
                                                    offset: '15px'
                                                    , icon: 2
                                                    , time: 3000
                                                });
                                                $('#ID-button-leader-addform-getLeaderByName').removeClass('layui-btn-disabled');
                                                return false;
                                            }

                                            //校验结果，无结果
                                            if (res.data.length == 0) {
                                                layer.msg('没有匹配到团长，请检查输入的团长名称是否准确完整！');
                                                $('#ID-button-leader-addform-getLeaderByName').removeClass('layui-btn-disabled');
                                                return false;
                                            }

                                            //校验结果，多条结果
                                            if (res.data.length > 1) {
                                                //layer.msg('匹配多个团长，请检查输入的团长名称是否准确完整！');
                                                //以单选框展示结果让用户选择哪一个

                                                var radioGroupHTML = `
                                                    <div class="layui-form-item">
                                                        <label class="layui-form-label"></label>
                                                        <div class="layui-input-block">
                                                        <p>匹配到多个团长，请您选择其中一个：</p>`;
                                                res.data.forEach(function (item) {
                                                    var itemJson = JSON.stringify(item);
                                                    radioGroupHTML += `
                                                        <input type="radio" name="apiOptions" value="${item.leaderId}" title="${item.name}" data-object='${itemJson}' lay-filter="leader-addform-radio-filter">`;
                                                });
                                                radioGroupHTML += `
                                                        </div>
                                                    </div>
                                                `;
                                                $('#ID-div-leader-addform-radioGroupContainer').html(radioGroupHTML);
                                                form.render('radio', 'layuiadmin-form-leaderadmin');

                                                $('#ID-button-leader-addform-getLeaderByName').removeClass('layui-btn-disabled');
                                                return false;
                                            }

                                            //匹配唯一一条结果时，设置团长ID和团长图标
                                            var resData = res.data[0];
                                            form.val('layuiadmin-form-leaderadmin', {
                                                "leaderId": resData.leaderId, // "name": "value"
                                            });
                                            $("#ID-img-leader-addform-iconUrl").attr("src", resData.iconUrl);
                                            $('#ID-button-leader-addform-getLeaderByName').removeClass('layui-btn-disabled');
                                        }
                                    });
                                }
                            });

                            //radio 事件
                            form.on('radio(leader-addform-radio-filter)', function (data) {
                                var elem = data.elem; // 获得 radio 原始 DOM 对象
                                var checked = elem.checked; // 获得 radio 选中状态
                                var value = elem.value; // 获得 radio 值
                                var othis = data.othis; // 获得 radio 元素被替换后的 jQuery 对象
                                console.log(elem);

                                // 获取自定义属性中的JSON字符串
                                var objectStr = $(data.elem).attr('data-object');
                                // 解析JSON字符串为对象
                                var obj = JSON.parse(objectStr);

                                //layer.msg(['value: ' + value, 'checked: ' + checked].join('<br>'));
                                form.val('layuiadmin-form-leaderadmin', {
                                    "leaderName": elem.title,
                                    "leaderId": value, // "name": "value"
                                });
                                $("#ID-img-leader-addform-iconUrl").attr("src", obj.iconUrl);
                            });

                            //开启提交
                            form.on('submit(LAY-leader-addform-submit)', function (data) {
                                var field = data.field; //获取提交的字段

                                //设置团长图像
                                var iconUrl = $("#ID-img-leader-addform-iconUrl").attr("src");
                                field.IconUrl = iconUrl;

                                console.log(field);

                                //AJAX请求
                                $.ajax({
                                    url: setter.baseConfig.apiHost + '/api/leader/add' //实际使用请改成服务端真实接口
                                    , type: 'post'
                                    , contentType: "application/json"
                                    , data: JSON.stringify(field)
                                    , beforeSend: function (xhr) {
                                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                                    }
                                    , success: function (res) {
                                        if (res.errorCode != '00000') {
                                            layer.msg(res.errorMessage, {
                                                offset: '15px'
                                                , icon: 2
                                                , time: 3000
                                            });
                                            return false;
                                        }

                                        //登入成功的提示与跳转
                                        layer.msg('新增成功', {
                                            offset: '15px'
                                            , icon: 1
                                            , time: 3000
                                        });

                                        layui.table.reload('LAY-leader-manage'); //重载表格
                                        layer.close(index);
                                    }
                                });
                            });
                        });
                    }
                });
                break;
        };
    });

    function getInvoiceDetail(myInvoiceId, billType, invoiceNumber) {
        var field = {
            myInvoiceId: myInvoiceId,
            billType: billType,
            invoiceNumber: invoiceNumber
        };
        let invoiceDetail;
        $.ajax({
            url: setter.baseConfig.apiHost + '/api/myinvoice/getinvoicedetail' //实际使用请改成服务端真实接口
            , type: 'post'
            , async: false //同步请求
            , contentType: "application/json"
            , data: JSON.stringify(field)
            , beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
            }
            , success: function (res) {
                if (res.errorCode != '00000') {
                    return;
                }

                invoiceDetail = res.data;
            }
        });

        return invoiceDetail;
    }

    //工具条，编辑和删除操作
    table.on('tool(LAY-leader-manage)', function (obj) {
        var data = obj.data;
        console.log(data);
        //var invoiceDetail = getInvoiceDetail(data.id, data.billType, data.invoiceNumber);
        if (obj.event === 'disable') {
            layer.confirm('确定要禁用吗？', function (index) {
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                $.ajax({
                    url: setter.baseConfig.apiHost + '/api/leader/disable'  //实际使用请改成服务端真实接口
                    , type: 'post'
                    , contentType: "application/json"
                    , data: JSON.stringify({
                        id: data.id,
                        isEnabled: 'N'
                    })
                    , beforeSend: function (xhr) {
                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                    }
                    , success: function (res) {
                        if (res.errorCode != '00000') {
                            layer.msg(res.errorMessage, {
                                offset: '15px'
                                , icon: 2
                                , time: 3000
                            });
                            return false;
                        }

                        //登入成功的提示与跳转
                        layer.msg('禁用成功', {
                            offset: '15px'
                            , icon: 1
                            , time: 3000
                        });

                        layui.table.reload('LAY-leader-manage'); //重载表格
                        layer.close(index); //执行关闭
                    }
                });
            });
        } else if (obj.event === 'enable') {
            layer.confirm('确定要启用吗？', function (index) {
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                $.ajax({
                    url: setter.baseConfig.apiHost + '/api/leader/disable' //实际使用请改成服务端真实接口
                    , type: 'post'
                    , contentType: "application/json"
                    , data: JSON.stringify({
                        id: data.id,
                        isEnabled: 'Y'
                    })
                    , beforeSend: function (xhr) {
                        xhr.setRequestHeader("Authorization", 'Bearer ' + layui.data(setter.tableName)[setter.request.tokenName]);
                    }
                    , success: function (res) {
                        if (res.errorCode != '00000') {
                            layer.msg(res.errorMessage, {
                                offset: '15px'
                                , icon: 2
                                , time: 3000
                            });

                            return false;
                        }

                        //登入成功的提示与跳转
                        layer.msg('启用成功!', {
                            offset: '15px'
                            , icon: 1
                            , time: 3000
                        });

                        layui.table.reload('LAY-leader-manage'); //重载表格
                        layer.close(index); //执行关闭
                    }
                });
            });
        } else if (obj.event === 'manageproduct') {
            //路由到商品管理页面，带着团长Id参数
            location.hash = '/product/list/leaderId=' + data.leaderId;
        }
    });

    // 行单击事件
    table.on('row(LAY-leader-manage)', function (obj) {
        var data = obj.data; // 得到当前行数据
        var dataCache = obj.dataCache; // 得到当前行缓存数据，包含特定字段 --- 2.8.8+
        var index = obj.index; // 得到当前行索引
        var tr = obj.tr; // 得到当前行 <tr> 元素的 jQuery 对象
        var options = obj.config; // 获取当前表格基础属性配置项
        var e = obj.e; // 当前的 jQuery 事件对象 --- 2.9.14+

        var isInvoiceNumberCol = e.target.classList.contains('billtong-myinvoice-table-invoicenumber');
        if (!isInvoiceNumberCol) {
            console.log('非ID列，阻止row事件.');
            return false;
        }
        console.log('onrow', data); // 查看返回对象的所有成员
        // obj.del() // 删除当前行
        // obj.update(fields, related);  // 修改行数据
        // obj.setRowChecked(opts); // 设置行选中状态

        //适配发票预览，先调用获取发票详情接口获取发票详情，然后打开预览窗口
        //let request = {
        //    myInvoiceId: data.id,
        //    billType: data.billType,
        //    invoiceNumber: data.invoiceNumber
        //};
        //common.doOpen(request);
        let arr = [{
            alt: "团长图片",
            pid: 1,
            src: data.imageUrl
        }];

        layer.photos({
            photos: {
                "title": "Photos Demo",
                "start": 0,
                "data": arr
            }
        });
    });

    //管理员管理
    table.render({
        elem: '#LAY-user-back-manage'
        , url: './res/json/useradmin/mangadmin.js' //模拟接口
        , cols: [[
            { type: 'checkbox', fixed: 'left' }
            , { field: 'id', width: 80, title: 'ID', sort: true }
            , { field: 'loginname', title: '登录名' }
            , { field: 'telphone', title: '手机' }
            , { field: 'email', title: '邮箱' }
            , { field: 'role', title: '角色' }
            , { field: 'jointime', title: '加入时间', sort: true }
            , { field: 'check', title: '审核状态', templet: '#buttonTpl', minWidth: 80, align: 'center' }
            , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
        ]]
        , text: '对不起，加载出现异常！'
    });

    //工具条
    table.on('tool(LAY-user-back-manage)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.prompt({
                formType: 1
                , title: '敏感操作，请验证口令'
            }, function (value, index) {
                layer.close(index);
                layer.confirm('确定删除此管理员？', function (index) {
                    console.log(obj)
                    obj.del();
                    layer.close(index);
                });
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '编辑管理员'
                , area: ['420px', '450px']
                , id: 'LAY-popup-myinvoice-batchupload'
                , success: function (layero, index) {
                    view(this.id).render('user/administrators/adminform', data).done(function () {
                        form.render(null, 'layuiadmin-form-admin');

                        //提交
                        form.on('submit(LAY-user-back-submit)', function (data) {
                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            //$.ajax({});
                            layui.table.reload('LAY-user-back-manage'); //重载表格
                            layer.close(index); //执行关闭 
                        });
                    });
                }
            });
        }
    });

    //角色管理
    table.render({
        elem: '#LAY-user-back-role'
        , url: './res/json/useradmin/role.js' //模拟接口
        , cols: [[
            { type: 'checkbox', fixed: 'left' }
            , { field: 'id', width: 80, title: 'ID', sort: true }
            , { field: 'rolename', title: '角色名' }
            , { field: 'limits', title: '拥有权限' }
            , { field: 'descr', title: '具体描述' }
            , { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-useradmin-admin' }
        ]]
        , text: '对不起，加载出现异常！'
    });

    //工具条
    table.on('tool(LAY-user-back-role)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('确定删除此角色？', function (index) {
                obj.del();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '添加新角色'
                , area: ['500px', '480px']
                , id: 'LAY-popup-myinvoice-batchupload'
                , success: function (layero, index) {
                    view(this.id).render('user/administrators/roleform', data).done(function () {
                        form.render(null, 'layuiadmin-form-role');

                        //提交
                        form.on('submit(LAY-user-role-submit)', function (data) {
                            var field = data.field; //获取提交的字段

                            //提交 Ajax 成功后，关闭当前弹层并重载表格
                            //$.ajax({});
                            layui.table.reload('LAY-user-back-role'); //重载表格
                            layer.close(index); //执行关闭 
                        });
                    });
                }
            });
        }
    });

    exports('leader', {})
});